package com.mvvmhabit.org.http

import android.util.MalformedJsonException
import com.google.gson.JsonParseException
import com.mvvmhabit.org.utils.ToastUtils
import org.apache.http.conn.ConnectTimeoutException
import org.json.JSONException
import retrofit2.HttpException
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.text.ParseException
import javax.net.ssl.SSLException

/**
 * @Date: 2020/12/14 9:40
 * @Author:小妖
 * @Description: 异常处理
 */
class ExceptionHandle {

    companion object {
        private const val UNAUTHORIZED: Int = 401
        private const val FORBIDDEN: Int = 403
        private const val NOT_FOUND: Int = 404
        private const val REQUEST_TIMEOUT: Int = 408
        private const val INTERNAL_SERVER_ERROR: Int = 500
        private const val SERVICE_UNAVAILABLE: Int = 503

        fun handleException(e: Throwable) {
            val ex: ResponseThrowable
            if (e is HttpException) {
                ex = ResponseThrowable(e, 1003)
                ex.message = "未知错误"
                when (e.code()) {
                    UNAUTHORIZED -> {
                        ex.message = "操作未授权"
                    }
                    FORBIDDEN -> {
                        ex.message = "请求被拒绝"
                    }
                    NOT_FOUND -> {
                        ex.message = "资源不存在"
                    }
                    REQUEST_TIMEOUT -> {
                        ex.message = "服务器执行超时"
                    }
                    INTERNAL_SERVER_ERROR -> {
                        ex.message = "服务器内部错误"
                    }
                    SERVICE_UNAVAILABLE -> {
                        ex.message = "服务器不可用"
                    }
                }
            } else if (e is JsonParseException || e is JSONException || e is ParseException || e is MalformedJsonException) {
                ex = ResponseThrowable(e, 1001)
                ex.message = "解析错误"
            } else if (e is ConnectException) {
                ex = ResponseThrowable(e, 1002)
                ex.message = "连接失败"
            } else if (e is SSLException) {
                ex = ResponseThrowable(e, 1005)
                ex.message = "证书验证失败"
            } else if (e is ConnectTimeoutException) {
                ex = ResponseThrowable(e, 1006)
                ex.message = "连接超时"
            } else if (e is SocketTimeoutException) {
                ex = ResponseThrowable(e, 1006)
                ex.message = "连接超时"
            } else if (e is UnknownHostException) {
                ex = ResponseThrowable(e, 1006)
                ex.message = "主机地址未知"
            } else {
                ex = ResponseThrowable(e, 1000)
                ex.message = "未知错误"
            }
          //  ToastUtils.showShort(ex.message)
            println("错误：" + ex.message)
        }
    }
}